package service

import (
	"fmt"
	"ginblog/config"
	errMsg "ginblog/model/err"
	"ginblog/utils"
	"github.com/aliyun/aliyun-oss-go-sdk/oss"
	"mime/multipart"
	"strings"
	"time"
)

func Upload(file *multipart.FileHeader) (string, errMsg.Code) {
	var (
		bucket   *oss.Bucket
		err      error
		f        multipart.File
		fileType string
		today    = time.Now().Format("20060102")
		fullPath string
	)

	bucket, err = utils.Oss.Bucket(config.Bucket)
	r := NewReturn()
	r.Check(err != nil, errMsg.OSS_UPLOAD_FAIL)
	r.CheckDo(func() {
		fileType = strings.ToLower(file.Filename[strings.LastIndex(file.Filename, "."):])
		f, err = file.Open()
	})
	r.Check(err != nil, errMsg.OSS_UPLOAD_FAIL)
	uid := utils.Uuid()
	path := fmt.Sprintf("%s/%s%s", today, uid, fileType)
	err = bucket.PutObject(path, f)
	r.Check(err != nil, errMsg.OSS_UPLOAD_FAIL)
	r.CheckDo(func() {
		fullPath = config.OssAddr + "/" + path
	})
	return fullPath, errMsg.SUCCESS
}
